/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.job.admin.controller;

import com.google.common.collect.Ordering;
import com.lvyh.lightframe.job.admin.annotation.PermitLimit;
import com.lvyh.lightframe.job.admin.bean.JobUserPermitBean;
import com.lvyh.lightframe.job.enums.ErrorCode;
import com.lvyh.lightframe.job.admin.util.DateUtils;
import com.lvyh.lightframe.job.common.Result;
import com.lvyh.lightframe.job.admin.model.JobPermitParam;
import com.lvyh.lightframe.job.admin.processor.JobManageProcessor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author lvyh 2021/04/11.
 */
@Controller
@RequestMapping("/permit")
public class PermitController extends BaseController {

    @Autowired
    private JobManageProcessor jobManageProcessor;

    @RequestMapping
    @PermitLimit(superAdmin = true)
    public String index(Model model) throws Exception {

        List<JobUserPermitBean> dataList = jobManageProcessor.getJobUserPermitList();
        dataList.sort(Ordering.natural().onResultOf(JobUserPermitBean::getUpdateTime));

        dataList.forEach(p -> p.setCreateTimeText(DateUtils.format(p.getCreateTime())));
        dataList.forEach(p -> p.setUpdateTimeText(DateUtils.format(p.getUpdateTime())));
        model.addAttribute("dataList", dataList);

        return "permit/list";
    }

    @RequestMapping("/save")
    @PermitLimit(superAdmin = true)
    @ResponseBody
    public Result<String> save(JobPermitParam param) throws Exception {

        Assert.notNull(param.getTaskId(), "TaskId must not be empty.");
        Assert.notNull(param.getUserId(), "UserId must not be empty.");

        JobUserPermitBean existEnv = jobManageProcessor.getJobUserPermitInfo(param.getTaskId(), param.getUserId());
        if (existEnv != null) {
            Result.create(ErrorCode.FAILED, "User permission already exists");
        }

        JobUserPermitBean jobUserPermitBean = new JobUserPermitBean();
        BeanUtils.copyProperties(param, jobUserPermitBean);

        int result = jobManageProcessor.saveJobUserPermitBean(jobUserPermitBean);
        return (result > 0) ? Result.SUCCESS() : Result.FAILED();
    }


    @RequestMapping("/update")
    @PermitLimit(superAdmin = true)
    @ResponseBody
    public Result<String> update(JobPermitParam param) throws Exception {

        Assert.notNull(param.getTaskId(), "TaskId must not be empty.");
        Assert.notNull(param.getUserId(), "UserId must not be empty.");

        JobUserPermitBean existUserPermit = jobManageProcessor.getJobUserPermitInfo(param.getTaskId(), param.getUserId());
        if (existUserPermit == null) {
            Result.create(ErrorCode.FAILED, "permit must not be null.");
        }

        BeanUtils.copyProperties(param, existUserPermit);
        boolean result = jobManageProcessor.updateJobUserPermitBean(existUserPermit);
        return (result) ? Result.SUCCESS() : Result.FAILED();
    }


    @RequestMapping("/remove")
    @PermitLimit(superAdmin = true)
    @ResponseBody
    public Result<String> remove(Integer taskId, Integer userId) throws Exception {

        Assert.notNull(taskId, "TaskId must not be empty.");
        Assert.notNull(userId, "UserId must not be empty.");

        boolean result = jobManageProcessor.deleteJobUserPermitBean(taskId, userId);
        return (result) ? Result.SUCCESS() : Result.FAILED();
    }


}
